package com.dataaccess.dataaccess.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.support.model.RespEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: YangYu
 * @ClassName: PaiAnSmokeGatewaysService
 * @Date: Created in 10:38 2021/10/27
 */
@Service
public class PaiAnSmokeGatewaysService extends BaseService {

    @Resource
    private AsyncService asyncService;
    /**
     * @Author YangYu
     * @Description 派安烟感网关数据处理
     * @Date Created in 14:35 2021/10/28
     * @Param [jsonParam]
     */

    public RespEntity smokeGateways(JSONObject jsonParam){
        //原数据
        String code = jsonParam.getStr("code");
        //指令
        String instruction = code.substring(8,10);
        //指令类型
        String instructionType = code.substring(28,30);
        //网关id a800220002ff0731303232313638010838393836303439333139323143303333363134399e
        String gatewayID  = new String(HexUtil.decodeHex(code.substring(14,28)));
        //防区设备id
        Integer deviceID = null;
        //返回指令
        String returnCode = "";
        //告警类别
        String alarmType = "";
        //报警内容
        String content = "";
        //报警标识
        boolean alarmFlag = false;
        //上报基本信息
        if ("0002".equals(code.substring(6,10))){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);
        }
        //上报基本信息
        if ("0005".equals(code.substring(6,10))){
            returnCode = "a8000b"+"01"+instruction+"01"+instructionType+timeTo16()+checkSum("01"+instruction+"01"+instructionType+timeTo16());
        }
        // 更新设备状态用
        boolean errorFlag = false;
        //上报信息
        if ("0007".equals(code.substring(6,10))){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);

            //上报配件信息
            if (instructionType.equals("02")){
                //配件设备号
                //deviceID = Integer.toHexString(Integer.parseInt(code.substring(30,32)));
                deviceID = Integer.parseInt(code.substring(30,32),16);
                //配件状态
                String accessoryStatus = code.substring(34,36);
                //报警类型
                alarmType = "烟感故障";
                if (accessoryStatus.equals("03")){
                    content = "配件丢失";
                    alarmFlag = true;
                    errorFlag = true;
                }else if (accessoryStatus.equals("04")){
                    content = "配件屏蔽";
                    alarmFlag = true;
                    errorFlag = true;
                }
            }
        }
        //上报信息
        if ("0003".equals(code.substring(6,10))){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);

            if (!"01".equals(instructionType) && !"0a".equals(instructionType)){
                //deviceID = Integer.toHexString(Integer.parseInt(code.substring(36,38)));
                deviceID = Integer.parseInt(code.substring(36,38),16);
            }

            if (code.substring(30,32).equals("01")){
                alarmType = "烟感火警";
                content = alarmTypeText(code.substring(34,36));
                alarmFlag = true;
            }else {
                alarmType = "烟感故障";
                content = errorTypeText(code.substring(34,36));
                alarmFlag = true;
            }
        }
        //报警
        if (alarmFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceClassify","3");
            if (deviceID != null){
                jsonObject.put("number",gatewayID+deviceID);
            }else {
                jsonObject.put("number",gatewayID);
            }
            jsonObject.put("interfaceType","1");
            jsonObject.put("alarmtime", DateUtil.now());
            jsonObject.put("alarmTypeName",alarmType);
            jsonObject.put("content",content);
            fireFightingiot(jsonObject,"communication","notificationAlarmHandel","alarmInfo");
            jsonObject.put("state","2");
            //异步更新传输装置状态
            asyncService.updateDeviceCurrentState(jsonObject);
        }
        //更新状态
        if (errorFlag){
            jsonParam.put("number",gatewayID+deviceID);
            jsonParam.put("state","3");
            //异步更新传输装置状态
            asyncService.updateDeviceCurrentState(jsonParam);
            fireFightingiot(jsonParam,"firefightingiot","updateGatewaysSmokeState","device");
        }
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number",gatewayID);
        jsonParamN.put("time",DateUtil.now());
        //异步更新部件状态
        asyncService.update_user_transmission_state(jsonParamN);
        return RespEntity.success(returnCode);
    }

    /**
     * @Author YangYu
     * @Description 派安烟感网关数据处理(网关新协议)
     * @Date Created in 14:35 2021/10/28
     * @Param [jsonParam]
     */

    public RespEntity smokeGatewaysNew(JSONObject jsonParam){
        //原数据
        String code = jsonParam.getStr("code");
        //指令
        String instruction = code.substring(8,10);
        //指令类型
        String instructionType = code.substring(28,30);
        //网关id a800220002ff0731303232313638010838393836303439333139323143303333363134399e
        String gatewayID  = new String(HexUtil.decodeHex(code.substring(14,28)));
        //防区设备id
        Integer deviceID = null;
        //返回指令
        String returnCode = "";
        //告警类别
        String alarmType = "";
        //报警内容
        String content = "";
        //报警标识
        boolean alarmFlag = false;

        //上报基本信息
        if ("0002".equals(code.substring(6,10))){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);
        }
        //上报基本信息
        if ("0005".equals(code.substring(6,10))){
            returnCode = "a8000b"+"01"+instruction+"01"+instructionType+timeTo16()+checkSum("01"+instruction+"01"+instructionType+timeTo16());
        }
        // 更新设备状态用
        boolean errorFlag = false;
        //上报信息
        if ("0007".equals(code.substring(6,10))){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);

            //上报配件信息
            if (instructionType.equals("02")){
                //配件设备号
                //deviceID = Integer.toHexString(Integer.parseInt(code.substring(30,32)));
                deviceID = Integer.parseInt(code.substring(30,32),16);
                //配件状态
                String accessoryStatus = code.substring(34,36);
                //报警类型
                alarmType = "烟感故障";
                if (accessoryStatus.equals("03")){
                    content = "配件丢失";
                    alarmFlag = true;
                    errorFlag = true;
                }else if (accessoryStatus.equals("04")){
                    content = "配件屏蔽";
                    alarmFlag = true;
                    errorFlag = true;
                }
            }
        }
        //上报信息
        if ("07".equals(instruction)){
            returnCode = "a80005"+"01"+instruction+"01"+instructionType+checkSum("01"+instruction+"01"+instructionType);

            if (!"01".equals(instructionType) && !"0a".equals(instructionType)){
                //deviceID = Integer.toHexString(Integer.parseInt(code.substring(36,38)));
                deviceID = Integer.parseInt(code.substring(36,38),16);
            }

            if (code.substring(30,32).equals("01")){
                alarmType = "烟感火警";
                content = alarmTypeText(code.substring(34,36));
                alarmFlag = true;
            }else {
                alarmType = "烟感故障";
                content = errorTypeText(code.substring(34,36));
                alarmFlag = true;
            }
        }
        //报警
        if (alarmFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceClassify","3");
            if (deviceID != null){
                jsonObject.put("number",gatewayID+deviceID);
            }else {
                jsonObject.put("number",gatewayID);
            }
            jsonObject.put("interfaceType","1");
            jsonObject.put("alarmtime", DateUtil.now());
            jsonObject.put("alarmTypeName",alarmType);
            jsonObject.put("content",content);
            //fireFightingiot(jsonObject,"communication","notificationAlarmHandel","alarmInfo");
            jsonObject.put("state","2");
            //异步更新传输装置状态
            //asyncService.updateDeviceCurrentState(jsonObject);
        }
        //更新状态
        if (errorFlag){
            jsonParam.put("number",gatewayID+deviceID);
            jsonParam.put("state","3");
            //异步更新传输装置状态
            //asyncService.updateDeviceCurrentState(jsonParam);
            //fireFightingiot(jsonParam,"firefightingiot","updateGatewaysSmokeState","device");
        }
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number",gatewayID);
        jsonParamN.put("time",DateUtil.now());
        //异步更新部件状态
        //asyncService.update_user_transmission_state(jsonParamN);
        return RespEntity.success(returnCode);
    }

    /**
     * @Author YangYu
     * @Description 派安网关（lora-智消云）
     * @Date Created in 10:35 2024/4/15
     * @Param [jsonParam]
     */

    public RespEntity smokeGatewaysLora(JSONObject jsonParam){

        //数据
        JSONObject devInfo = jsonParam.getJSONObject("devInfo");
        JSONObject iotMsg = jsonParam.getJSONObject("iotMsg");
        //设备编号
        String number = iotMsg.getStr("devId");
//        if (StrUtil.isNotBlank(devInfo.getStr("dpDetailAddr"))){
//            String[] dpDetailAddr = devInfo.getStr("dpDetailAddr").split("区");
//            number = number+dpDetailAddr[0];
//        }
        if (iotMsg.containsKey("detail")){
            JSONObject detail = iotMsg.getJSONObject("detail");
            if (detail.containsKey("siteId")){
                number = number+detail.getStr("siteId");
            }
        }
        // 预警类型
        int msgType = iotMsg.getInt("msgType");
        // 报警描述
        String msgDesc = iotMsg.getStr("msgDesc");
        //告警类别
        String alarmType = "";
        //报警内容
        String content = "";
        //报警标识
        boolean alarmFlag = false;
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number",number);
        if (msgType == 2){
            alarmType = "烟感火警";
            content = msgDesc;
            alarmFlag = true;
            jsonParamN.put("state","2");
            //异步更新传输装置状态
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else if (msgType == 3){
            alarmType = "烟感故障";
            content = msgDesc;
            alarmFlag = true;
            jsonParamN.put("state","2");
            //异步更新传输装置状态
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        if (alarmFlag){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("deviceClassify","3");
            jsonObject.put("number",number);
            jsonObject.put("interfaceType","1");
            jsonObject.put("alarmtime", DateUtil.now());
            jsonObject.put("alarmTypeName",alarmType);
            jsonObject.put("content",content);
            fireFightingiot(jsonObject,"communication","notificationAlarmHandel","alarmInfo");
        }else {
            jsonParamN.put("time",DateUtil.now());
            //异步更新部件状态
            asyncService.update_user_transmission_state(jsonParamN);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 派安网关返回指令校验和
     * @Date Created in 14:38 2021/10/28
     * @Param [code]
     */

    public static String checkSum(String code){
        int sum = 0;
        for (int i = 0; i < code.length(); i=i+2) {
            String codes = code.substring(i,i+2);
            sum = sum+Integer.parseInt(codes, 16);
        }
        String strSum = Integer.toHexString(sum);

        if (strSum.length()<=1){
            strSum = "0"+strSum;
        }
        return strSum;
    }
    /**
     * @Author YangYu
     * @Description 16进制时间（年月日时分秒）
     * @Date Created in 17:36 2021/10/28
     * @Param []
     */

    public static String timeTo16(){
        String[] waterTime = DateUtil.now().split(" ");
        String date = waterTime[0];
        String[] dateCode = date.split("-");
        String ms = waterTime[1];
        String[] msCode = ms.split(":");
        String code = dateCode[0].substring(2) + dateCode[1] + dateCode[2] + msCode[0] + msCode[1] + msCode[2];
        String returnCode = "";
        for (int i = 0; i < code.length(); i=i+2) {
            String codes = code.substring(i,i+2);
            String code1 = Integer.toHexString(Integer.parseInt(codes));
            if (code1.length()==1){
                code1 = "0"+code1;
            }
            returnCode = returnCode+code1;
        }
        return returnCode;
    }

    /**
     * @Author YangYu
     * @Description 报警类型名称
     * @Date Created in 15:47 2021/10/28
     * @Param [code]
     */

   public String alarmTypeText(String code){
       Map<String,String> map = new HashMap<>();
       map.put("03","发生火警");
       map.put("05","温度报警");
       map.put("08","SOS报警");
       map.put("09","电气报警");
       map.put("0a","水压报警");
       map.put("0b","手报报警");
       map.put("0c","一氧化碳报警");
       map.put("0d","烟温报警");
       map.put("0f","燃气泄漏");
       map.put("3e","联动报警");
       map.put("40","主机防拆报警");
       map.put("4f","测试");
       map.put("ee","有线防区报警");
       return map.get(code);
   }

   /**
    * @Author YangYu
    * @Description 故障类型
    * @Date Created in 15:52 2021/10/28
    * @Param [code]
    */

    public String errorTypeText(String code){
        Map<String,String> map = new HashMap<>();
        map.put("03","烟感丢失");
        map.put("05","温感丢失");
        map.put("08","按钮丢失");
        map.put("09","电气丢失");
        map.put("0a","水压丢失");
        map.put("0b","手报丢失");
        map.put("0c","一氧化碳丢失");
        map.put("0d","烟温丢失");
        map.put("0f","燃气丢失");
        map.put("13","烟感低电");
        map.put("15","温感低电");
        map.put("18","按钮低电");
        map.put("1b","手报低电");
        map.put("1c","一氧化碳低电");
        map.put("1d","烟温低电");
        map.put("1f","燃气故障");
        map.put("2d","烟温拆开");
        map.put("40","备电故障");
        map.put("41","主电故障");
        map.put("42","无线模块故障");
        map.put("43","GSM模块故障");
        map.put("44","备电低电");
        return map.get(code);
    }
}
